﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Appcode;

namespace MyWeb
{
    public partial class AlbumManager1 : System.Web.UI.Page
    {
        private ProductsDAL objProd = new ProductsDAL();
      

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtAlbumName.Visible = false;
                btnCreate.Visible = false;
                uploadAlbum.Visible = false;
                loadAlbum();
                loadImgData();
                loadCartInfo();
            }
        }

        protected void btnupload_Click(object sender, EventArgs e)
        {

            if (DropDownList1.SelectedIndex == 0 || DropDownList1.SelectedItem.Text.Equals("--Select--"))
            {
                imginfo.Attributes.CssStyle.Value = "color:red;font-size:16px;font-weight:bold;";
                imginfo.Text = "Please chose album for store Image.";
                return;
            }

            if (myFileUpload.HasFile)
            {
                String username = Session.GetLoginUser().UserName;
                int countUploaded = 0;
                int countUploadFail = 0;
                int maxFileUploadSeting = 10;

                String uploadFolder = "UploadFolder\\" + username;
                String uploadPath = Server.MapPath(uploadFolder);

                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                HttpFileCollection hfc = Request.Files;

                if (hfc.Count <= maxFileUploadSeting)
                {
                    for (int i = 0; i < hfc.Count; i++)
                    {
                        HttpPostedFile hpf = hfc[i];

                        if (hpf.ContentLength > 0)
                        {
                            if (!File.Exists(uploadPath + "\\" + Path.GetFileName(hpf.FileName)))
                            {
                                DirectoryInfo objDir = new DirectoryInfo(uploadPath + "\\");
                                String sFileName = Path.GetFileName(hpf.FileName);
                                String sFileExt = Path.GetExtension(hpf.FileName);


                                //CHECK DUPLICATE
                                FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + ".*");

                                if (objFI.Length > 0)
                                {
                                    // CHECK IF FILE WITH THE SAME NAME EXISTS (IGNORING THE EXTENTIONS).
                                    foreach (FileInfo file in objFI)
                                    {
                                        string sFileName1 = objFI[0].Name;
                                        string sFileExt1 = Path.GetExtension(objFI[0].Name);

                                        if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))
                                        {
                                            countUploadFail += 1;        // NOT ALLOWING DUPLICATE.
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    // SAVE THE FILE IN A FOLDER.
                                    hpf.SaveAs(uploadPath + "\\" + Path.GetFileName(hpf.FileName));
                                    countUploaded += 1;
                                    Images img = new Images();
                                    img.AlbumName = DropDownList1.SelectedItem.Text;
                                    img.ImgName = Path.GetFileName(hpf.FileName);
                                    img.ImgPath = uploadFolder + "\\" + Path.GetFileName(hpf.FileName);
                                    objProd.SaveUpload(img);
                                }

                            }

                        }
                    }

                    String msg = "Uploaded: " + countUploaded + " files";

                    if (countUploaded == 0)
                    {
                        msg += ":There are duplicate error file in  the files uploaded.";
                    }

                    if (countUploadFail > 0)
                    {
                        msg += ":Duplicate: " + countUploadFail + " files";
                    }

                    imginfo.Attributes.CssStyle.Value = "color:green;font-size:16px;font-weight:bold;";
                    imginfo.Text = msg;

                }
                else
                {
                    imginfo.Attributes.CssStyle.Value = "color:red;font-size:16px;font-weight:bold;";
                    imginfo.Text = "There are too much files...(max can does:)" + maxFileUploadSeting + " files";
                }

            }
            else
            {
                imginfo.Attributes.CssStyle.Value = "color:red;font-size:16px;font-weight:bold;";
                imginfo.Text = "No files was selected.";
            }
        }

        public void loadAlbum()
        {
            DropDownList1.Items.Clear();
            DropDownList2.Items.Clear();
            DropDownList1.Items.Add("--Selected--");
            DropDownList2.Items.Add("All Pictures");
            List<String> album = objProd.getALbumName(Session.GetLoginUser().UserID);
            if (album != null)
            {
                foreach (String item in album)
                {
                    DropDownList1.Items.Add(item);
                    DropDownList2.Items.Add(item);
                }
            }
        }
        protected void btncreateAB_Click(object sender, EventArgs e)
        {
            txtAlbumName.Visible = true;
            btnCreate.Visible = true;
            btncreateAB.Visible = false;
        }
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            String albumName = txtAlbumName.Text;

            if (albumName != null && !albumName.Equals(""))
            {
                bool flag = false;
                List<String> album = objProd.getALbumName(Session.GetLoginUser().UserID);
                if (album != null)
                {
                    foreach (String item in album)
                    {
                        if (item.Equals(albumName))
                        {
                            flag = true;
                            break;
                        }
                    }
                }

                if (flag == true)
                {
                    imginfo.Attributes.CssStyle.Value = "color:red;font-size:16px;font-weight:bold;";
                    imginfo.Text = "Album Name has been existed,chose other name!";
                }
                else
                {
                    objProd.createAlbumName(Session.GetLoginUser().UserID, albumName);
                    imginfo.Attributes.CssStyle.Value = "color:green;font-size:16px;font-weight:bold;";
                    imginfo.Text = "The album Name: " + albumName + " has been created!";
                    txtAlbumName.Visible = false;
                    btnCreate.Visible = false;
                    btncreateAB.Visible = true;
                }

                loadAlbum();
            }
            else
            {
                imginfo.Attributes.CssStyle.Value = "color:red;font-size:16px;font-weight:bold;";
                imginfo.Text = "Album Name required not null.";
            }
        }
        protected void btnUploadImg_Click(object sender, EventArgs e)
        {
            uploadAlbum.Visible = true;
            showAlbum.Visible = false;
        }

        public void loadImgData()
        {
            List<Images> listImg = objProd.getAllImagesByUID(Session.GetLoginUser().UserID);

            GridView1.DataSource = listImg;

            GridView1.DataBind();
        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            loadImgData();
        }

        public List<String> getSizes()
        {
            return objProd.getProductsSize();
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "add2cart")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                String imgID = GridView1.DataKeys[index].Values[0].ToString();
                String albumName = GridView1.DataKeys[index].Values[1].ToString();
                String imgName = GridView1.DataKeys[index].Values[2].ToString();
                String imgPath = GridView1.DataKeys[index].Values[3].ToString();
                DropDownList ddl = (DropDownList)GridView1.Rows[index].FindControl("DropDownList3");
                String imgSize = ddl.SelectedItem.Text;


                Images anImage = new Images();
                anImage.ImageID = Convert.ToInt32(imgID);
                anImage.AlbumName = albumName;
                anImage.ImgName = imgName;
                anImage.ImgPath = imgPath;
                anImage.ImgSize = imgSize;

                String[] sizes = imgSize.Split('x');
                float cost = objProd.getCostOfSize(Convert.ToInt32(sizes[0]), Convert.ToInt32(sizes[1]));
                anImage.UnitPrice = cost;

                List<Images> listCart = CartProcessing(anImage);
                Session.SetShopingCart(listCart);

                Response.Redirect("Cart1.aspx");
            }
        }

        public List<Images> CartProcessing(Images img)
        {
            List<Images> curList = Session.GetShopingCart();

            if (curList != null)//has data
            {
                bool flag = false;//not contain
                for (int i = 0; i < curList.Count; i++)
                {
                    if (img.ImageID == curList[i].ImageID)
                    {
                        flag = true;//has contain
                        curList[i].ImgSize = img.ImgSize;
                        curList[i].UnitPrice = img.UnitPrice;
                        curList[i].ImgQuantity = curList[i].ImgQuantity + 1;
                        break;
                    }
                }

                if (flag == false)
                {
                    img.ImgQuantity = 1;
                    curList.Add(img);
                }
            }
            else
            {//or not
                curList = new List<Images>();
                img.ImgQuantity = 1;
                curList.Add(img);
            }

            return curList;
        }


        public void loadCartInfo()
        {
            List<Images> listCart = Session.GetShopingCart();
            float totalPrice = 0;
            int totalProduct = 0;

            if (listCart != null)
            {
                for (int i = 0; i < listCart.Count; i++)
                {
                    totalPrice += listCart[i].UnitPrice * listCart[i].ImgQuantity;
                }

                totalProduct = listCart.Count;
            }

            choseinfo.Text = "Current chosen: " + totalProduct + " products";
            costinfo.Text = "Total cost: " + totalPrice.ToString() + "$";
        }
    }
}